<?php

namespace app\controller;

use think\facade\Request;
use think\facade\Db;
use think\facade\View;
use think\facade\Session;
use think\facade\Cookie;
use Hashids\Hashids;
use app\AuthController;

use app\model\Article as ArticleModel;
use app\model\{
  User as UserModel,
  ContentArticle as ContentArticleModel,
  Comment as CommentModel,
};

use app\BaseInfoController as BaseInfo;

class Article extends AuthController
{
  # 用户文章管理综合功能

  ############################################################ 公共页展示博客文章 ###############################################################################
  # 公共页展示博客文章
  public function article($akey)
  {
    $user = $this->request->adminInfo;

    # 传入公共变量
    $site_info = BaseInfo::siteInfo();
    View::assign([
      'user' => $user,
      'site_info'     => $site_info,  // 网站信息
      'main_nav_menu' => BaseInfo::mainNavMenu(), // 主导航
      'vice_nav_menu' => BaseInfo::viceNavMenu(), // 副导航
      'menu' => null, // 首页导航ID
    ]);

    // 转换文章ID
    $articleId = $this->getArticleKey($akey);
    if (!$articleId) return View::fetch('mz_blog/404');

    // 查询文章内容
    $articleData = ContentArticleModel::where('status', 2)->withoutField('content')->find($articleId);
    if (is_null($articleData))
      $articleData = ContentArticleModel::where($this->request->select)->withoutField('content')->find($articleId);

    // 检查文章是否存在
    if (!is_null($articleData)) {
      $articleData = $articleData->toArray();
      ContentArticleModel::where('id', $articleId)->inc('pageviews')->update();
      // 记录浏览者信息

    } else {
      return View::fetch('mz_blog/404');
    }

    # 传入公共变量
    View::assign([
      'title'   => $articleData['title'] . ' - 【' . $site_info['site_name'] . '】',
    ]);

    # 找到文章渲染模板并输出
    switch ($articleData['template_type']) {
      case 'mz_article': // 木桩网络博客默认文章模版
        return $this->articleTemplateMuzhuang($articleData);
        break;
      case 'mz_article_long': // 木桩网络博客宽屏文章模版
        return $this->articleTemplateMuzhuangLong($articleData);
        break;
      default:
        return $this->articleTemplateMuzhuang($articleData);
    }
  }
  // 木桩网络博客默认文章模版
  protected function articleTemplateMuzhuang($article)
  {
    // 获取此文章的留言信息
    $comment = CommentModel::where('far_id', $article['id'])->where('prev', '0')->order('time desc')->select()->toArray();
    $coreply = CommentModel::where('far_id', $article['id'])->where('prev', '<>', '0')->order('time asc')->select()->toArray();
    foreach ($comment as $key => $value) {
      foreach ($coreply as $k => $vol) {
        if ($vol['prev'] == $value['id']) {
          $comment[$key]['zclass'][] = $vol;
          unset($coreply[$k]);
        }
      }
    }

    $touristInfo = Cookie::get('tourist-info');
    View::assign([
      'comment' => $comment, //此文章评论
      'isAdmin' => $this->request->sellerId === 1,
      'touristInfo' => $touristInfo ? unserialize($touristInfo) : null,
    ]);

    // 网站专栏名称
    $websiteCategory = BaseInfo::websiteCategory();
    $article['category'] = $websiteCategory['name'][$article['website_category']] ?? '待设置';

    return View::fetch('mz_blog/article', [
      'article' => $article,
      'hotacl'  => ContentArticleModel::getHotList(), // 热门文章
      'erysts'  => BaseInfo::everydayPhrases(), // 每日一句
      'prev'    => ContentArticleModel::getPrevArticle($article['website_category'], $article['publish_time']), // 上一篇
      'next'    => ContentArticleModel::getNextArticle($article['website_category'], $article['publish_time']), // 下一篇
      'abouts'  => ContentArticleModel::getHotList(),  // 相关推荐
    ]);
  }
  // 木桩网络博客宽屏文章模版
  protected function articleTemplateMuzhuangLong($article)
  {
    return View::fetch('mz_blog/article_long', [
      'article' => $article,
      // 'isProhibit' => 1, // 禁止复制
    ]);
  }

  #############################################################################################################################################################
  # 文章点赞
  public function json_article_like()
  {
    if ($this->request->isPost()) {
      $aid  = $this->request->post('aid/s');
      $result = Db::name('article')->where('aid', $aid)->where('state', '>', 1)->where('state', '<', 4)->inc('like')->update();
      if (!$result) {
        $result = Db::name('article')->where('aid', $aid)->where('state', '>', 1)->where('state', '<', 4)->update(['like' => 1]);
      }
      if ($result) {
        return json(['state' => 'success']);
      } else {
        return json(['state' => 'error']);
      }
    }
  }
  # 此文章浏览记录
  public function article_browse()
  {
    # 获取用户登录信息和文章UID
    $user = $this->request->adminInfo;
    $aid  = $this->request->param('aid/s');
    // if(isset($user['limit']) && in_array('DRy', explode(',',$user['limit']))){
    if (1) {
      $result = Db::table('so_website_request')->where('request_code', 'Qxj')->where('info1', $aid)->order('time desc')->select()->toArray();
      $article = Db::table('so_article')->where('aid', $aid)->field('id,aid,title')->find();
      $u1 = Db::table('so_user')->column('nick', 'uid');
      $u2 = Db::table('so_user_tourist')->column('nick', 'uid');
      $usernick = array_merge($u1, $u2);
      View::assign([
        'result' => $result,
        'article' => $article,
        'unick' => $usernick,
      ]);
      return View::fetch('article/article_browse');
    } else {
      return '<h2>您没有权限查看文章浏览记录</h2>';
    }
  }
  # json删除文章浏览记录
  public function json_delete_article_browse()
  {
    if ($this->request->isPost()) {
      $id = $this->request->post('id/s');
      $result = Db::table('so_website_request')->delete($id);
      if ($result)
        return json(['state' => 'success']);
      else
        return json(['state' => 'error']);
    }
  }




  ############################################################ 博客文章列表页 ##################################################################################
  # 博客文章列表页
  public function list($mainId)
  {
    // 登录账号信息
    $user = $this->request->adminInfo;

    // 传入公共变量
    View::assign([
      'user' => $user,
      'site_info'     => BaseInfo::siteInfo(),  // 网站信息
      'main_nav_menu' => BaseInfo::mainNavMenu(), // 主导航
      'vice_nav_menu' => BaseInfo::viceNavMenu(), // 副导航
      'menu' => null, // 首页导航ID
    ]);

    // 验证网站专栏
    $category = array_column(config('contenthelper.Category'), 'name', 'id');
    if (!isset($category[$mainId]))
      return View::fetch('mz_blog/404');
    View::assign([
      'categoryName' => $category[$mainId],
    ]);

    // 文章列表
    $where['page'] = $this->request->param('page/d') ?? 1;
    $where['limit'] = 10;
    $list = ContentArticleModel::getSubList($mainId, $where);

    // 网站信息
    $site_info = BaseInfo::siteInfo();

    # 传入变量并渲染模版
    View::assign([
      'user'  => $user,       // 登录用户信息
      'p_name' => $category[$mainId], // 栏目名称
      'title'  => $category[$mainId] . ' - 【' . $site_info['site_name'] . '】', // 网站标题
      'articl' => $list, // 文章列表
      'hotacl' => ContentArticleModel::getHotList(), // 热门文章
      'erysts' => BaseInfo::everydayPhrases(), // 每日一句
      'page'   => ++$where['page'],   // 文章分页
      'site_info'     => $site_info,  // 网站信息
      'main_nav_menu' => BaseInfo::mainNavMenu(), // 主导航
      'vice_nav_menu' => BaseInfo::viceNavMenu(), // 副导航
      'menu' => 18, // 首页导航ID
    ]);
    return View::fetch('mz_blog/list');
  }
  #############################################################################################################################################################






  #############################################################################################################################################################
  # 搜索页面
  public function search()
  {
    # 获取登录用户信息
    $user = $this->request->adminInfo;

    $keys = $this->request->param('keys/s');

    $article = ContentArticleModel::getSearchList([], $this->request->select, $keys);

    # 网站信息
    $site_info = BaseInfo::siteInfo();
    $p_name    = '关键词“ ' . $keys . ' ”的搜索结果，共搜索到' . count($article) . '条记录';

    # 传入变量并渲染模版
    View::assign([
      'user'  => $user,    // 登录用户信息
      'p_name' => $p_name, // 栏目名称
      'title'  => $p_name . ' - 【' . $site_info['site_name'] . '】', // 网站标题
      'articl' => $article, // 文章列表
      'hotacl' => ContentArticleModel::getHotList(), // 热门文章
      'erysts' => BaseInfo::everydayPhrases(), // 每日一句
      // 'page'   => $page,   // 文章分页
      'site_info'     => $site_info,  // 网站信息
      'main_nav_menu' => BaseInfo::mainNavMenu(), // 主导航
      'vice_nav_menu' => BaseInfo::viceNavMenu(), // 副导航
      'websiteCategory' => BaseInfo::websiteCategory(), // 网站专栏
      'menu' => 0, // 首页导航ID
    ]);
    return View::fetch('mz_blog/search');
  }



























































  ################################################################ 极简文章栏目 ################################################################################
  # 极简文章栏目
  public function article_column()
  {
    # 获取登录用户信息
    $user = $this->request->adminInfo;

    # 获取当前分组请求种类ID
    $groupId = $this->request->param('groupId/d');

    # 按分组查询文章
    if ($groupId > 0) {
      $far_id = Db::table('pub_portal_category')->where('id', $groupId)->value('far_id');
      if ($far_id > 0) {
        $article = Db::name('article')->order('rel_order desc')->where('rel_id', $groupId)->select()->toArray();
      } else {
        $article = null;
        $far_id = null;
      }
    } else {
      $article = null;
      $far_id = null;
    }
    # 获取全部分组及数量信息
    $group_top = Db::table('pub_portal_category')->where('far_id', 0)->order('link_order desc')->select()->toArray();
    $group_bot = Db::table('pub_portal_category')->where('far_id', '<>', 0)->order('link_order desc')->select()->toArray();
    foreach ($group_top as $key => $vol) {
      foreach ($group_bot as $k => $v) {
        if ($vol['id'] == $v['far_id']) {
          $group_top[$key]['zclass'][] = $v;
          unset($group_bot[$k]);
        }
      }
    }
    $all_links = Db::name('article')->where('state', 3)->where('rel_id', 'not null')->column('rel_id'); //查询全部链接信息以获取分组条数情况
    foreach ($group_top as $key => $vol) {
      $group_top[$key]['ct'] = 0;
      if (isset($vol['zclass'])) {
        foreach ($vol['zclass'] as $k => $v) {
          $group_top[$key]['zclass'][$k]['ct'] = 0;
          foreach ($all_links as $ke => $va) {
            if ($va == $v['id']) {
              $group_top[$key]['ct'] += 1;
              $group_top[$key]['zclass'][$k]['ct'] += 1;
              unset($all_links[$ke]);
            }
          }
        }
      }
    }

    # 会员名和会员头像
    $unick = Db::name('user')->column('nick', 'uid'); //会员昵称UID索引

    # 赋值并渲染输出
    View::assign([
      'user'  => $user,       // 登录用户信息
      'unick' => $unick,      // 会员昵称UID索引
      'group' => $group_top,  // 全部分组
      '_type' => $far_id, // 分组类型
      'article' => $article,  // 文章列表
      'aclenum' => null,  // 文章数量
      'article_menu' => null,
      'site_info'     => BaseInfo::siteInfo(),  // 网站信息
      'main_nav_menu' => BaseInfo::mainNavMenu(), // 主导航
      'vice_nav_menu' => BaseInfo::viceNavMenu(), // 副导航
      'menu' => null,                            // 导航ID
    ]);
    return View::fetch('home_template/minimalism_article_category');
  }
  #################################### 【文章编辑模块】 写文章/编辑文章 、 JSON保存编辑的文章 、 编辑器上传图片三个模块 #################################################
  # 写文章/编辑文章
  public function writer()
  {
    # 获取登录用户信息
    $user = $this->request->adminInfo;

    #处理编辑器编辑文章或新增文章
    $etp = $this->request->param('editortype/s');
    $aid = $this->request->param('articleId/s');
    if ($etp === null && $aid !== null && preg_match('/^[_0-9a-zA-Z]{5}$/', $aid)) { //默认编辑此文章处理
      $article = Db::name('article')->where('uid', $user['uid'])->where('aid', $aid)->where('delete_time', null)->findOrEmpty();
      if (!empty($article)) {
        View::assign([
          'user'    => $user,
          'article' => $article,
        ]);
        switch ($article['editortype']) {
          case 'editormd':
            return View::fetch('writer_editormd');
            break;
          case 'ckeditor5':
            return View::fetch('writer_ckeditor5');
            break;
          case 'handyeditor':
            return View::fetch('writer_handyeditor');
            break;
          default:
            echo '<h1>服务器错误：未指定编辑器类型，您可以截图联系博主哦</h1>';
        }
      } else {
        echo '<h1>亲爱的' . $user['nick'] . '童鞋，此文章不存在哦</h1>';
      }
    } else if ($etp !== null && $aid === null) { //默认按照某种编辑器新建文章
      View::assign([
        'user'    => $user,
        'article' => null,
      ]);
      switch ($etp) {
        case 'editormd':
          return View::fetch('writer_editormd');
          break;
        case 'ckeditor5':
          return View::fetch('writer_ckeditor5');
          break;
        case 'handyeditor':
          return View::fetch('writer_handyeditor');
          break;
        default:
          echo '<h1>亲爱的' . $user['nick'] . '童鞋，您的访问链接有问题，做个乖孩纸，不要手动修改URL</h1>';
      }
    } else if ($etp === null && $aid === null) { //打开默认编辑器新建文章
      View::assign([
        'user'    => $user,
        'article' => null,
      ]);
      $editor = Db::name('user')->where('uid', $user['uid'])->value('default_editor');
      switch ($editor) {
        case 'editormd':
          return View::fetch('writer_editormd');
          break;
        case 'ckeditor5':
          return View::fetch('writer_ckeditor5');
          break;
        case 'handyeditor':
          return View::fetch('writer_handyeditor');
          break;
        default:
          echo '<h1>服务器错误：未指定编辑器类型，您可以截图联系博主哦</h1>';
      }
    } else {
      echo '<h1>亲爱的' . $user['nick'] . '童鞋，您的访问链接有问题，做个乖孩纸，不要手动修改URL</h1>';
    }
  }
  # JSON保存编辑的文章
  public function preservation()
  {
    $user_id = Session::get('user.uid');

    #如果有表单提交
    if ($this->request->isPost()) {
      $article_id           = $this->request->post('articleId/s');
      $data['title']        = $this->request->post('title/s');
      $data['test_content'] = $this->request->post('test_markdown');
      $data['test_html']    = $this->request->post('test_html');
      $editor               = $this->request->post('editor/s');
      $data['update_time']  = date("Y-m-d h:i:s", time());
      if (empty($data['title'])) return json(['state' => 'error', 'str' => '文章标题不能为空']);
      #判断新增还是修改录入数据库
      if (empty($article_id)) {
        switch ($editor) {
          case 'md':
            $data['editortype'] = 'editormd';
            break;
          case 'ck':
            $data['editortype'] = 'ckeditor5';
            break;
          case 'he':
            $data['editortype'] = 'handyeditor';
            break;
          default:
            return json(['state' => 'error', 'str' => '未指定编辑器']);
        }
        $data['create_time']  = date("Y-m-d h:i:s", time());
        $data['uid'] = $user_id;
        $data['state'] = 1;
        $data['template'] = 'mz_blog';
        // return json(['state'=>'error','str'=>$article_id]);
        #获取排序link_order最大值
        $p_order = Db::name('article')->where('uid', $user_id)->max('p_order');
        $p_order += 1;
        $data['p_order'] = (int)$p_order;
        $resultid = Db::name('article')->insertGetId($data);
        if ($resultid) {
          $Hashids = new Hashids('soyulsmida', 5);
          $artclid = $Hashids->encode($resultid);
          Db::name('article')->where('id', $resultid)->update(['aid' => $artclid]);
          return json(['state' => 'insert', 'articleId' => $artclid, 'str' => '新增文章成功']);
        } else {
          return json(['state' => 'error', 'str' => '新增文章失败，请重试']);
        }
      } else {
        // return json(['state'=>'error','str'=>$article_id]);
        $result = Db::name('article')->where('uid', $user_id)->where('aid', $article_id)->update($data);
        if ($result) {
          return json(['state' => 'success', 'str' => '文章保存成功']);
        } else {
          return json(['state' => 'error', 'str' => '文章那写入失败，请重试']);
        }
      }
    }
  }
  #JSON_Editor.md编辑器上传图片
  public function json_upl_articlepic_edi()
  {
    #上传图片，这里缺少了个验证图片的功能
    $file = request()->file('editormd-image-file');
    $savename = \think\facade\Filesystem::disk('public')->putFile('', $file);
    if ($savename) {
      $data['success'] = 1;
      $data['message'] = '图片上传成功';
      $data['url']     = '/storage/' . $savename;
    } else {
      $data['success'] = 0;
      $data['message'] = '图片上传失败';
    }
    return json($data);
  }
  #JSON_ckeditor5编辑器上传图片
  public function json_upl_articlepic_ck5()
  {
    #检测用户登陆
    $Login = new Login($this->app);
    $user = $Login->check_login();
    if (!$user) return json(["uploaded" => 0]);
    #上传图片，这里缺少了个验证图片的功能
    $file = request()->file('upload');
    $savename = \think\facade\Filesystem::disk('public')->putFile('', $file);
    if ($savename) {
      return json(["uploaded" => 1, "url" => '/storage/' . $savename]);
    } else {
      return json(["uploaded" => 0]);
    }
  }
  #JSON_HandyEditor编辑器上传图片
  public function json_upl_articlepic_he()
  {
    #上传图片，这里缺少了个验证图片的功能
    $file = request()->file('file');
    $savename = \think\facade\Filesystem::disk('public')->putFile('', $file);
    if ($savename) {
      echo '/storage/' . $savename;
      die;
    }
  }
  ######################################################################################################################################################
}
